from ninja import Router, Schema

router = Router()

# 给查询参数
@router.get("/hello")
def hello(request, name):
    return f"Hello {name}"

# 查询参数，类型校验
@router.get("/hello")
def hello(request, name:str='word'):
    return f"Hello {name}"

# 添加查询参数并指定类型
@router.get("/math")
def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}

# 传递路径参数
@router.get("/math/{a}and{b}")
def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}


# POST方法，给schema


class HelloSchema(Schema):
    name: str = "world"

@router.post("/hello")
def hello(request, data: HelloSchema):
    return f"Hello {data.name}"


"""
前端无论传递哪些类型的数据，均会自动转为指定类型。除非传递字母转换不了
{
    "foo": "nnn",
    "bar": 1
}

{
    "foo": "nnn",
    "bar": "1"
}
"""
class Item(Schema):
    foo: str
    bar: float

@router.post('/item')
def item(request,x:Item):
    return {'result': x}


# 转换响应，django queryset/object 转响应
class UserSchema(Schema):
    username: str
    is_authenticated: bool
    # Unauthenticated users don't have the following fields, so provide defaults.
    email: str = None
    first_name: str = None
    last_name: str = None
    # 不需要响应密码
    # password: str




# 响应1种类型
from django.contrib.auth.models import User
@router.get("/me", response=UserSchema)
def me(request):
    admin = User.objects.first()
    print(admin.__dict__)
    return admin

class Error(Schema):
    message: str

# 响应2种类型
@router.get("/meinfo", response={200: UserSchema,403: Error})
def me(request):
    if not request.user.is_authenticated:
        return 403, {'message': '请登入'}
    admin = User.objects.first()
    print(admin.__dict__)
    return admin # 相当于　200, admin


